package models

import "github.com/jinzhu/gorm"

type Article struct {
	Model

	TagID int `json:"tag_id" gorm:"index"`
	Tag Tag `json:"tag"`

	Title string `json:"title"`
	Desc string `json:"desc"`
	Content string `json:"content"`
	CoverImageUrl string `json:"cover_image_url"`
	CreatedBy string `json:"created_by"`
	ModifiedBy string `json:"modified_by"`
	State int `json:"state"`
}

func ExistArticleByID(id int) bool {
	var article Article
	db.Select("id").Where("id=?",id).First(&article)
	if article.ID>0{
		return true
	}
	return false
}
//获取文章总数
func GetArticleTotal(maps interface{}) (count int) {
	db.Model(&Article{}).Where(maps).Count(&count)
	return
}
//获取文章列表
func GetArticles(pageNum int, pageSize int, maps interface{}) (articles []*Article,err error) {
	err =db.Preload("Tag").Where(maps).Offset(pageNum).Limit(pageSize).Find(&articles).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return articles,err
}
func GetArticle(id int) (*Article,error) {
	var article Article
	err :=db.Where("id=? AND deleted_on = ?",id,0).First(&article).Error
	if err!=nil && !gorm.IsRecordNotFoundError(err){
		return nil, err
	}
	err = db.Model(&article).Related(&article.Tag).Error
	if err!=nil && err!=gorm.ErrRecordNotFound{
		return nil, err
	}
	return &article,nil
}
func EditArticle(id int, data interface {}) error {
	if err :=db.Model(&Article{}).Where("id = ?", id).Updates(data).Error;err!=nil{
		return err
	}
	return nil
}

func AddArticle(data map[string]interface {}) error {
	err :=db.Create(&Article {
		TagID : data["tag_id"].(int),
		Title : data["title"].(string),
		Desc : data["desc"].(string),
		Content : data["content"].(string),
		CoverImageUrl: data["cover_image_url"].(string),
		CreatedBy : data["created_by"].(string),
		State : data["state"].(int),
	}).Error

	if err!=nil{
		return err
	}
	return nil
}

func DeleteArticle(id int) error {
	if err:=db.Where("id = ?", id).Delete(Article{}).Error;err!=nil{
		return err
	}
	return nil
}

func CleanAllArticle() bool {
	db.Unscoped().Where("deleted_on != ? ", 0).Delete(&Article{})

	return true
}



